<?php

namespace app\Common\model;

use think\Model;

class City extends Model
{
    //获取城市信息
    public function getNormalCitysByParentId($id = 0)
    {
        $data = [
            'parent_id' => $id,
            'status' => 1
        ];
        $order = [
            'id' => 'desc',
        ];
        $result = $this->where($data)->order($order)->select();
//        echo $this->getLastSql();
        return $result;
    }

    //获取市级的城市信息
    public function getNormalCitys()
    {
        $data = [
            'status' => 1,
            'parent_id' => ['gt', 0],
        ];
        return $this->where($data)->select();
    }

    public function getTree()
    {
        $data = collection($this->where(['status' => 1])->select())->toArray();
        return $this->getSourseTree($data);
    }

    public function getSourseTree($data, $parent_id = 0, $level = 1)
    {
        static $tree = [];
        foreach ($data as $v) {
            if ($parent_id == $v['parent_id']) {
                $v['level'] = $level;
                $tree[$v['id']] = $v;
                $this->getSourseTree($data, $v['id'], $level + 1);
            }
        }
        return $tree;
    }
}
